package com.fengxu.gamescript.ui.log

import android.animation.ValueAnimator
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.TextView
import androidx.core.view.marginBottom
import androidx.core.view.marginEnd
import androidx.core.widget.NestedScrollView
import com.fengxu.gamescript.R
import com.fengxu.gamescript.data.GlobalData
import com.fengxu.gamescript.data.LogChangeType
import com.fengxu.gamescript.data.LogEvent
import com.fengxu.gamescript.jsengine.core.JsRunnerLog
import com.fengxu.gamescript.ui.base.BaseActivity
import com.xuexiang.xui.utils.DensityUtils
import org.jetbrains.anko.sdk27.coroutines.onClick
import org.joda.time.DateTime

class LoggerActivity : BaseActivity() {

    /**
     * 存放日志的布局
     */
    private val logLayout: LinearLayout by lazy {
        findViewById(R.id.log_mainLayout)
    }

    /**
     * 滚动布局
     */
    private val scrollView: NestedScrollView by lazy {
        findViewById(R.id.log_scroll)
    }

    /**
     * 清除所有日志的悬浮窗
     */
    private val flowWin: View by lazy {
        findViewById<View>(R.id.log_clearAll)
    }

    // 日志改变事件实现类实例
    private val logChangedEvent by lazy { MyLogEvent() }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_logger)
        initView()
    }

    private fun initView() {
        flowEnterAnim()
        findViewById<View>(R.id.actionbar_back).onClick { finish() }
        findViewById<TextView>(R.id.actionbar_title).text = "日志"
        // 清除日志事件
        flowWin.onClick {
            GlobalData.clearAllLog()
        }
        // 监听日志改变
        loadScriptLog()
        GlobalData.logChanged.add(logChangedEvent)
    }

    private inner class MyLogEvent: LogEvent{
        // 日志改变事件
        override fun changed(type: LogChangeType, log: JsRunnerLog?) {
            uiHandler.post {
                if(type == LogChangeType.Clear){
                    logLayout.removeAllViews()
                }else{
                    addLogView(log!!)
                }
            }
        }
    }

    /**
     * 加载脚本日志
     */
    private fun loadScriptLog(){
        logLayout.removeAllViews()
        GlobalData.getLogList().forEach {
            addLogView(it)
        }
    }

    /**
     * 追加一条日志信息
     */
    private fun addLogView(log: JsRunnerLog){
        val tv = TextView(this).apply {
            text = "[${log.name}]: ${log.msg}  -- ${DateTime(log.logTime).toString("HH:mm:ss")}"
            val lp = LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            lp.bottomMargin = DensityUtils.dp2px(10F)
            layoutParams = lp
            textSize = 18F
            when(log.logLevel){
                JsRunnerLog.LogLevel.System -> setTextColor(Color.parseColor("#CCCCCC"))
                JsRunnerLog.LogLevel.Info -> setTextColor(Color.BLACK)
                JsRunnerLog.LogLevel.Error -> setTextColor(Color.RED)
            }
        }
        logLayout.addView(tv)
        uiHandler.post { scrollView.fullScroll(ScrollView.FOCUS_DOWN) }
    }

    /**
     * 设置悬浮窗进入动画
     */
    private fun flowEnterAnim() {
        val lp = flowWin.layoutParams
        var valueAnimator = ValueAnimator.ofInt(0, lp.height)
        valueAnimator.duration = 500
        valueAnimator.addUpdateListener {
            lp.width = it.animatedValue as Int
            lp.height = it.animatedValue as Int
            flowWin.layoutParams = lp
            flowWin.requestLayout()
        }
        valueAnimator.start()
    }

    override fun onDestroy() {
        GlobalData.logChanged.remove(logChangedEvent)
        super.onDestroy()
    }

}